/* ===================

AX2E (AXESCON XACML 2.0 Engine) is the Java authorization engine, which implements OASIS XACML 2.0 standard.
Copyright (C) 2007 AXESCON LLC

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA


Contact: AXESCON LLC - info{at}axescon.com

 =================== */
package axescon.xacml.xb.ctx;


import axescon.xacml.model.policy.AttributeSelector;
import axescon.xacml.model.policy.PolicyObject;
import axescon.xacml.model.policy.impl.AttributeSelectorImpl;
import org.apache.xmlbeans.XmlCursor;
import x0PolicySchemaOs.oasisNamesTcXacml2.AttributeSelectorType;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Date: Sep 30, 2005
 *         Responsibilities:
 */
public class XBAttributeSelectorFactory {


    public AttributeSelector getAttributeSelector(AttributeSelector template, AttributeSelectorType xbat, PolicyObject parent) throws Exception {
        if (xbat == null) return null;

        template.setDataType(xbat.getDataType());
        if (xbat.isSetMustBePresent()) template.setMustBePresent(xbat.getMustBePresent());

        String xpath = xbat.getRequestContextPath();
        XmlCursor cur = xbat.newCursor();
        Map map = new TreeMap();
        cur.getAllNamespaces(map);
        cur.dispose();

        String xqNamespace = "";

        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry en = (Map.Entry) it.next();
            xqNamespace += " declare namespace " + en.getKey() + "='" + en.getValue() + "'; ";
        }
        xpath = xqNamespace + xpath;

        template.setRequestContextPath(xpath);
        template.setParentPolicyObject(parent);
        return template;
    }

    public AttributeSelector getAttributeSelector(AttributeSelectorType xbat, PolicyObject parent) throws Exception {
        if (xbat == null) return null;
        AttributeSelector ret = null;
        ret = new AttributeSelectorImpl();
        return getAttributeSelector(ret, xbat, parent);
    }

}
